const qiniu = require('qiniu')
const _config = require('../config')

/*****
*  upload component
*  @param  : file 文件路径, key 文件别名
*  @return :  (返回值说明)
*****/

// "/Users/apple/node/koa-demo/mmjpg/static/img/1.jpg"
// 'girl.jpg'
const uploadImg = (file, key) => {
    // 基础配置
    var mac = new qiniu.auth.digest.Mac(
        _config.qiniu.accessKey,
        _config.qiniu.secretKey);
    var options = {
        scope: _config.qiniu.imgBucket
    };
    var putPolicy = new qiniu.rs.PutPolicy(options);
    var uploadToken=putPolicy.uploadToken(mac);

    // 服务器直传 七牛
    var config = new qiniu.conf.Config();
    // 空间对应的机房
    config.zone = qiniu.zone.Zone_z2;
    // 是否使用https域名
    // config.useHttpsDomain = true;
    // 上传是否使用cdn加速
    // config.useCdnDomain = true;
    var localFile = file;
    var formUploader = new qiniu.form_up.FormUploader(config);
    var putExtra = new qiniu.form_up.PutExtra();

    // 文件上传
    return new Promise((resolve, reject)=>{
        formUploader.putFile(uploadToken, key, localFile, putExtra,
            function(respErr, respBody, respInfo) {
            if (respErr) {
                // throw respErr;
                reject(respErr)
            }
            if (respInfo.statusCode == 200) {
                console.log(respBody);
                resolve({
                    code: 200,
                    hash: respBody['hash'],
                    key: respBody['key'],
                    url: _config.qiniu.backUrl +'/'+ respBody['key']
                })
            } else {
                console.log(respInfo.statusCode);
                console.log(respBody);
                resolve({
                    code: respInfo.statusCode,
                    respBody: respBody
                })
            }
        });
    })   
}
module.exports = uploadImg